package org.example.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.example.config.RabbitMQConfig;
import org.example.controller.request.AccountLoginRequest;
import org.example.controller.request.AccountRegisterRequest;
import org.example.enums.AuthTypeEnum;
import org.example.enums.BizCodeEnum;
import org.example.enums.EventMessageTypeEnum;
import org.example.enums.SendCodeEnum;
import org.example.manager.AccountManager;
import org.example.model.AccountDO;
import org.example.model.EventMessage;
import org.example.model.LoginUser;
import org.example.service.AccountService;
import org.example.service.NotifyService;
import org.example.util.CommonUtil;
import org.example.util.IDUtil;
import org.example.util.JWTUtil;
import org.example.util.JsonData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description:
 * @author: 谢超
 * @date: 2023/07/16 20:19
 **/
@Service
@Slf4j
public class AccountServiceImpl implements AccountService {

    @Resource
    private NotifyService notifyService;

    @Resource
    private AccountManager accountManager;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private RabbitMQConfig rabbitMQConfig;

    /**
     * 免费流量包id固定是1
     */
    private static final Long FREE_TRAFFIC_PRODUCT_ID = 1L;

    /**
     * 手机验证码校验
     * 密码加密
     * 账号唯一性检查
     * 插入数据库
     * 新注册用户福利发放
     * @param accountRegisterRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public JsonData register(AccountRegisterRequest accountRegisterRequest) {
        boolean checkCode = false;

        // 判断验证码
        if(StringUtils.isNoneBlank(accountRegisterRequest.getPhone())) {
            checkCode = notifyService.checkCode(SendCodeEnum.USE_REGISTER, accountRegisterRequest.getPhone(), accountRegisterRequest.getCode());
        }

        // 验证码错误
        if (!checkCode) {
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }

        AccountDO accountDO = new AccountDO();
        BeanUtils.copyProperties(accountRegisterRequest, accountDO);
        // 认证级别
        accountDO.setAuth(AuthTypeEnum.DEFAULT.name());

        // 生成唯一的账号，这里借助雪花算法
        accountDO.setAccountNo(Long.valueOf(IDUtil.geneSnowFlakeID().toString()));

        // 密码设置 密钥 盐
        accountDO.setSecret("$1$" + CommonUtil.getStringNumRandom(8));
        String cryptPwd = Md5Crypt.md5Crypt(accountRegisterRequest.getPwd().getBytes(), accountDO.getSecret());
        accountDO.setPwd(cryptPwd);

        int row = accountManager.insert(accountDO);

        log.info("rows:{},注册成功:{}", row, accountDO);

        // 用户注册成功发放福利
        userRegisterInitTask(accountDO);

        return JsonData.buildSuccess();
    }

    /**
     * 用户登录
     * 1.根据手机号去找
     * 2.
     * @param request
     * @return
     */
    @Override
    public JsonData login(AccountLoginRequest request) {
        List<AccountDO> accountDOList = accountManager.findByPhone(request.getPhone());
        log.info("---accountDOList:{}", accountDOList);
        if (accountDOList != null && accountDOList.size() == 1) {
            // 取出List第一位
            AccountDO accountDO = accountDOList.get(0);
            String md5Crypt = Md5Crypt.md5Crypt(request.getPwd().getBytes(), accountDO.getSecret());
            if (md5Crypt.equalsIgnoreCase(accountDO.getPwd())) {
                LoginUser loginUser = LoginUser.builder().build();
                // 将accountDO属性值复制给，loginUser中与它相同的属性
                BeanUtils.copyProperties(accountDO, loginUser);

                // 生成token
                String token = JWTUtil.geneJsonWebToken(loginUser);

                return JsonData.buildSuccess(token);
            } else {
                return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
            }
        } else {
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
        }
    }

    /**
     * 用户初始化发放福利(流量包)，使用mq的方式发送消息
     * @param accountDO
     */
    private void userRegisterInitTask(AccountDO accountDO) {
        EventMessage eventMessage = EventMessage.builder()
                .messageId(IDUtil.geneSnowFlakeID().toString())
                .accountNo(accountDO.getAccountNo())
                .eventMessageType(EventMessageTypeEnum.TRAFFIC_INIT_FREE.name())
                .bizId(FREE_TRAFFIC_PRODUCT_ID.toString())
                .build();

        rabbitTemplate.convertAndSend(rabbitMQConfig.getTrafficEventExchange(), rabbitMQConfig.getTrafficFreeInitRoutingKey(), eventMessage);
    }
}
